﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Ninject;
using Meraz.Core.Data;
using PetaPoco;

namespace Meraz.Core.Repositories
{
    public interface IFacebookTopicRepository
    {

        FacebookTopic GetById(long boardID, int topicID);
        List<FacebookTopic> GetByBoardId(long boardID);
        void Add(FacebookTopic entity);
        void Delete(FacebookTopic entity);
        List<FacebookTopic> All();
        void Save(FacebookTopic topic);
    }
    public class FacebookTopicRepository : IFacebookTopicRepository
    {
        [Inject]
        public Database DB { get; set; }
        #region IFacebookTopicRepository Members

        public FacebookTopic GetById(long boardID, int topicID)
        {
            return DB.FirstOrDefault<FacebookTopic>("where BoardID=@0 AND ID=@1", boardID, topicID);
        }

        public List<FacebookTopic> GetByBoardId(long boardID)
        {
            return DB.Query<FacebookTopic>(@"select t.ID AS ID,t.BoardID AS BoardID,t.Title AS Title,t.Poster AS Poster,t.CreatedDateTicks AS CreatedDateTicks,ticks_to_date_fn(t.CreatedDateTicks) AS CreatedDate,t.Url AS Url,t.TotalPosts AS TotalPosts,t.UniqueUsers AS UniqueUsers,t.Status AS Status,t.HasLink AS HasLink,t.Bad AS Bad,min(p.ID) AS FirstPostID 
 from facebooktopic t 
 join facebookpost p on p.TopicID = t.ID and p.BoardID = t.BoardID 
 left join facebooklink l on l.PostID = p.ID and l.TopicID = p.TopicID and l.BoardID = p.BoardID 
 where p.include=1 and (l.broadcast='' or l.citation='' or l.old='')
 group by t.ID,t.BoardID,t.Title,t.Poster,t.CreatedDateTicks,CreatedDate,t.Url,t.TotalPosts,t.UniqueUsers,t.Status,t.HasLink,t.Bad", boardID).ToList();
        }


        public void Add(FacebookTopic entity)
        {
            DB.Save(entity);
        }

        public void Delete(FacebookTopic entity)
        {
            DB.Delete<FacebookTopic>(entity);
        }

        public void Save(FacebookTopic entity)
        {
            var a = DB.SingleOrDefault<FacebookTopic>("SELECT * FROM facebooktopic WHERE ID=@0 AND BoardID=@1", entity.ID, entity.BoardID);
            if (a == null)
            {
                DB.Insert(entity);
            }
            else
            {
                DB.Update(entity);
            }
        }

        public List<FacebookTopic> All()
        {
            return DB.Query<FacebookTopic>("select * from facebooktopic").ToList();
        }

        #endregion
    }
}
